package com.yxcz.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import com.yxcz.model.User;
import com.yxcz.service.LoginService;

@Controller
@RequestMapping("/authorization")
public class AuthorizationLoginController {

	@Resource
	private LoginService loginService;

	@RequestMapping(value = "/qqLogin")
	public String qqLogin(HttpServletRequest request) {

		try {
			return "redirect:" + new Oauth().getAuthorizeURL(request);
		} catch (QQConnectException e) {
			e.printStackTrace();
		}
		return null;

	}

	@RequestMapping(value = "/doQQLogin")
	public ModelAndView doQQLogin(ModelAndView modelAndView, HttpServletRequest request, HttpSession session,RedirectAttributes attr) {

		try {
			AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
			OpenID openIDObj = new OpenID(accessTokenObj.getAccessToken());

			if (loginService.getUserByQQOpenId(openIDObj.getUserOpenID()).size()== 0) {
				attr.addAttribute("openid",openIDObj.getUserOpenID());
				attr.addAttribute("bindType","QQ");
				modelAndView.setViewName("redirect:/authorization/binding");
				return modelAndView;
			}

			session.setAttribute("accountName",
					loginService.getUserByQQOpenId(openIDObj.getUserOpenID()).get(0).getAccountName());
			modelAndView.setViewName("redirect:/Admin/index");
			return modelAndView;
		} catch (QQConnectException e) {
			modelAndView.setViewName("redirect:/Common/500Page");
			return modelAndView;
		}

	}
	
	@RequestMapping(value = "/binding")
	public ModelAndView binding(String openid,String bindType,ModelAndView modelAndView) {
		
		modelAndView.addObject("openid",openid);
		modelAndView.addObject("bindType",bindType);
		modelAndView.setViewName("User/BindingPage");
		return modelAndView;

	}
	
	@RequestMapping(value = "/doBinding")
	public ModelAndView doBinding(String openid,String bindType,User user,ModelAndView modelAndView) {
		try {
			User rtuser = loginService.authorizationLogin(user);
			loginService.bind(rtuser,bindType,openid);
			modelAndView.setViewName("redirect:/Admin/index");
			return modelAndView;
		} catch (Exception e) {
		
			modelAndView.addObject("accountName", user.getAccountName());
			modelAndView.addObject("errorMsg", "登录失败,请检查用户名或密码是否正确或帐号是否启用!");
			modelAndView.addObject("openid",openid);
			modelAndView.addObject("bindType",bindType);
			modelAndView.setViewName("User/BindingPage");
			return modelAndView;
		}
		

	}

}
